<template>
	<view class="poRel minH100v">
		<navbar background="background-image: linear-gradient(to right, #2c6739, #99c043);"
			title="首页" @topTotalHeight="topTotalHeight"
		></navbar>
		<view class="backImgLiGrTR2c6739a99c043 pl20r pr20r pt90r pb2r">
			<view class="disFlex aliItCenter f24r poFixed wPer100 left0 boSiBorBox pl20r pr20r backImgLiGrTR2c6739a99c043 zIndex1 h110r pt20r pb20r"
				:style="'top: ' + calcNum + 'px;'"
			>
				<view class="flex1 backColWhite borRad10r lh70r disFlex aliItCenter">
					<view class="w200r teAliCenter poRel webLiCl1 webBoxOrVer overHid disWebBox"
						@click="cliCityFun"
					>
						<image :src="baseUrl + 'iconLocationGreen.png'" mode="aspectFit"
							class="w30r h30r poRel top6r"
						></image>
						{{cityText}}
						<text class="poAbs rig0 top50P trTr0n50P w2r h40r backColE5e5e5"
						></text>
					</view>
					<view class="flex1 col999 teAliCenter webLiCl1 webBoxOrVer overHid disWebBox"
						@click="cliSearchInp"
					>
						<image :src="baseUrl + 'iconMagnifierBlack.png'" mode="aspectFit"
							class="w30r h30r poRel top4r"
						></image>
						{{searchText}}
					</view>
				</view>
				<view class="w50r h50r backColWhite borRad10r ml20r teAliCenter lh46r col999"
					@click="goUrl('/pages/index/proximityAndHistory')"
				>
					☰
				</view>
			</view>
			<view class="disFlex mt40r colFff teAliCenter f28r">
				<view class="flex1" @click="cliDoorGreen">
					<view class="w100r h100r boSiBorBox pt22r backColWhite borRad10r mAuto mb15r">
						<image :src="baseUrl + 'iconDoorGreen.png'" mode="aspectFit"
							class="w50r h50r"
						></image>
					</view>
					开门码
				</view>
				<view class="flex1" @click="cliRenewalGreen">
					<view class="w100r h100r boSiBorBox pt22r backColWhite borRad10r mAuto mb15r">
						<image :src="baseUrl + 'iconRenewalGreen.png'" mode="aspectFit"
							class="w50r h50r"
						></image>
					</view>
					再续单
				</view>
				<view class="flex1" @click="goUrl('/pages/index/walletList')">
					<view class="w100r h100r boSiBorBox pt22r backColWhite borRad10r mAuto mb15r">
						<image :src="baseUrl + 'iconComeRecharge.png'" mode="aspectFit"
							class="w50r h50r"
						></image>
					</view>
					来充值
				</view>
			</view>
			<swiper class="mt30r h300r bSha0a15a10an5rgba0a0a0as8 mb30r" :indicator-dots="true" :autoplay="true"
				v-if="bannerList.length"
			>
				<swiper-item v-for="item in bannerList" :key="item.id">
					<image :src="item.path" mode="aspectFill"
						class="wPer100 hPer100 borRad10r"
						@click="cliBannrImg(item)"
					></image>
				</swiper-item>
			</swiper>
			<uni-notice-bar single scrollable showIcon :fontSize="16"
				background-color="transparent" color="#ffffff"
				v-if="noticeVal" :text="noticeVal"
			></uni-notice-bar>
		</view>
		<view class="backColF5f5f5 pl20r pr20r pb40r">
			<scroll-view scroll-x="true" class="pt20r pb20r whSpaNow f28r">
				<view @click="cliTeaHouseBtn(index, item.id)" v-for="(item, index) in teaHourseAry" :key="index"
					:class="['mr26r', 'disInBlo', 'lh60r', 'poRel', 'pl15r', 'pr15r', 'backColWhite',
						'borRad10r', teaHouseIdx == index ? 'col99c043 foWeiBold' : ''
					]"
				>
					{{item.name}}
				</view>
			</scroll-view>
			<view class="backColWhite borRad10r pl10r pt10r pr10r mb20r"
				v-for="(item1, index1) in tesHourseList" :key="item1.id"
				@click="openRoomList(item1.openVal, index1, item1.id)"
			>
				<view class="disFlex pb10r borB1SF5f5f5">
					<view class="w180r h180r poRel borRad10r overHid">
						<image :src="item1.banZero" mode="aspectFill"
							class="wPer100 hPer100 borRad10r"
						></image>
						<view class="colFff backCol0a0a0aS5 poAbs top0 left0 lh40r f24r w60r teAliCenter borBRRad10r">
							自营
						</view>
					</view>
					<view class="flex1 pl10r">
						<view class="foWeiBold webLiCl1 webBoxOrVer overHid disWebBox f32r">
							{{item1.name}}
						</view>
						<view class="f24r h40r disFlex mt25r">
							<view class="flex1 disFlex borR1SE5e5e5 pr20r lh40r">
								<image :src="baseUrl + 'iconLocationGray.png'" mode="aspectFit"
									class="w40r h40r"
								></image>
								<view class="flex1 webLiCl1 webBoxOrVer overHid disWebBox h38r"
									@click.stop="cliAddress(item1.lat, item1.lon, item1.name, item1.address)"
								>
									{{item1.address}}
								</view>
							</view>
							<view class="w70r teAliCenter">
								<image :src="baseUrl + 'iconPhoneBlack.png'" mode="aspectFit"
									class="w40r h40r" @click.stop="cliPhoneBlack(item1.tel)"
								></image>
							</view>
						</view>
						<view class="disFlex aliItCenter h70r mt10r">
							<view class="flex1 f24r foWeiBold">
								营业时间：00:00-24:00
							</view>
							<view class="w135r lh60r backCol2c6739 colFff teAliCenter borRad35r floRight f28r foWeiBold"
								@click.stop="cliTeaList(item1)"
							>
								预订
							</view>
						</view>
					</view>
				</view>
				<view class="lh70r disFlex col99c043"
				>
					<view class="flex1 foWeiBold pl10r">
						距我：{{item1.distance}}km
					</view>
					<view class="w200r teAliRight f24r">
						{{
							item1.openVal ? '收起' : '展开'
						}}房间
						<image :src="baseUrl + (item1.openVal ? 'iconTopGreen' : 'iconBottomGreen') + '.png'"
							class="w40r h40r poRel top10r" mode="aspectFit"
						></image>
					</view>
				</view>
				<roomList v-if="item1.openVal" @cliUseNow="cliUseNow"
					:roomList="item1.roomList"
					@cliAdvanceReservation="cliAdvanceReservation"
				></roomList>
			</view>
			<view class="lh100r teAliCenter col999" v-if="tesHourseList.length == 0">
				暂无茶室
			</view>
		</view>
		<view class="poAbs top0 left0 bom0 left0 backCol0a0a0aS5 wPer100"
			v-show="cityFrame"
		>
			<view class="h500r poFixed left0 wPer100 backColWhite"
				:style="'top: ' + (calcNum + 55) + 'px;'"
			>
				<scroll-view scroll-y class="h400r">
					<view :class="['pl20r', 'pr20r', 'borB1SF0f0f0', 'lh100r',
							index === cityIndex ? 'col99c043' : ''
						]" @click="cliCityAry(index)"
						v-for="(item, index) in cityAry" :key="index"
					>
						{{item.city}}
					</view>
				</scroll-view>
				<view class="lh100r teAliCenter col99c043 borT1SF0f0f0 boSiBorBox"
					@click="cityFrame = false"
				>
					<image :src="baseUrl + 'iconTopGreen.png'" mode="aspectFit"
						class="w50r h50r poRel top12r"
					></image>
					关闭
				</view>
			</view>
		</view>
		<view class="poFixed wPer100 hPer100 backCol0a0a0aS5 zIndex1 top0 left0"
			v-show="popupAnnouncementFrame" @touchmove.stop.prevent
		>
			<view
				class="poFixed top50P left50P trTrn50Pn50P backColC5a083 borRad30r w600r h700r boSiBorBox bSha0010u0Fff bor1SCdb7a9 colFff"
			>
				<image :src="baseUrl + 'iconCloseWhite.png'" mode="aspectFit"
					class="w70r h70r poAbs rig0 topn100r" @click="popupAnnouncementFrame = false"
				></image>
				<view class="wPer99 hPer99 backColCdb7a9 poAbs top50P left50P trTrn50Pn50P borRad30r">
					<view class="wPer99 hPer99 backColC5a083 poAbs top50P left50P trTrn50Pn50P borRad30r">
						<view class="wPer99 hPer99 backColCdb7a9 poAbs top50P left50P trTrn50Pn50P borRad30r">
							<view class="wPer99 hPer99 backImgLiGrTR2c6739a99c043 poAbs top50P left50P trTrn50Pn50P borRad30r overHid disFlex flDirColumn">
								<view class="lh100r foWeiBold teAliCenter f40r">
									<text class="mr20r">
										公
									</text>
									告
								</view>
								<view class="flex1 overYS pl40r pr40r">
									<scroll-view scroll-y="true" class="hPer100">
										<view class="lh50r" v-show="index != popupAnnouncementAry.length - 1 && index != popupAnnouncementAry.length - 2"
											v-for="(item, index) in popupAnnouncementAry" :key="index"
										>
											{{item}}
										</view>
									</scroll-view>
								</view>
								<view class="h100r">
									<view class="teAliCenter colFff mt15r letSpa2r f30r webLiCl1 webBoxOrVer overHid disWebBox"
										@click="cliPopupAnnouncementClose"
									>
										<view class="lh70r h70r backImgLiGrTRB57c68aCfe3d7 mAuto disInBlo maxWPer100 borRad35r pl20r pr20r">
											{{
												popupAnnouncementAry && popupAnnouncementAry.length ? popupAnnouncementAry[popupAnnouncementAry.length - 2] : '我知道了'
											}}
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<haveInHandList @cliClose="cliClose" :departureType="departureType"
			:departureFrame="departureFrame" :departureList="departureList"
			@openShareFrame="openShareFrame" ref="haveInHandList"
		></haveInHandList>
		<shareFrame @cliCloseShare="cliCloseShare" :showShareFrame="showShareFrame"
			:shareCode="shareCode" :shareType="shareType"
		></shareFrame>
		<rightOffPage v-show="rightOffFrame" @closeRightOff="closeRightOff"
			:rightOffObj="rightOffObj" ref="rightOffPage"
		></rightOffPage>
		<advanceBookingPage v-show="advanceBookingFrame" ref="advanceBookingPage"
			@closeAdvanceBooking="closeAdvanceBooking"
			:advanceBookingObj="advanceBookingObj"
		></advanceBookingPage>
	</view>
</template>

<script>
import navbar from '@/components/navbar.vue'
import roomList from '@/components/roomList.vue'
import { mapNavigation } from '@/utils/utils.js'
import rightOffPage from '@/components/rightOffPage.vue'
import advanceBookingPage from '@/components/advanceBookingPage.vue'
import { isMemberGetTeaList, isMemberGetTeaRoomList,
	getcity, getBannmerApiPosition,
	getMemberNoticeInfo, getSwitchCode, getOffMemberNotice } from '@/utils/api.js'
import { baseUrl, imgNetUrl } from '@/utils/request.js'
import { QQMapWX } from '@/utils/qqmap-wx-jssdk.js'
import haveInHandList from '@/components/haveInHandList.vue'
import shareFrame from '@/components/shareFrame.vue'
export default {
	components: {
		navbar, roomList, rightOffPage, advanceBookingPage, haveInHandList,
		shareFrame
	},
	data() {
		return {
			token: '',
			baseUrl,
			calcNum: 0,
			cityChangeLonLat: '',
			cityText: '城市', cityFrame: false, cityIndex: '',
			cityAry: ['附近', '海口市', '南安市', '泉州市', '莆田市', '漳州市', '揭阳市', '三明市'],
			searchText: '搜索位置查找附近®共享茶室',
			departureType: 1, departureFrame: false, departureList: [],
			bannerList: [],
			popupAnnouncementFrame: false, popupAnnouncementAry: [],
			noticeVal: '',
			teaHourseAry: [
				{name: '全部', id: ''}, {name: '共享茶室', id: 1},
				{name: '即将开业', id: 2}
			],
			teaHourseId: '', lngAndLat: {},
			teaHouseIdx: 0,
			tesHourseList: [],
			rightOffFrame: false,
			rightOffObj: {
				topIsWho: 1,
				hourMin: '',
				hourMax: 24,
				tid: '',
				rid: '',
				setMealId: '',
				setMealMoney: 0,
				cardDiscount: '',
				originalCost: ''
			},
			advanceBookingFrame: false,
			advanceBookingObj: {
				topIsWho: 1,
				tid: '',
				rid: '',
				hour: '',
				setMealId: '',
				setMealMoney: 0,
				cardDiscount: '',
				originalCost: ''
			},
			shareCode: '', showShareFrame: false, shareType: 1
			
		}
	},
	onLoad(options) {
		if(options.shareCode) {
			this.shareCode = options.shareCode;
			this.shareType = 2;
			this.showShareFrame = true;
		}
		getMemberNoticeInfo().then(res => {
			if(res.data && res.data.text) this.noticeVal = res.data.text;
		})
		getcity().then(res => {
			this.cityAry = res.data;
		})
		if(uni.getStorageSync('lngAndLat')) this.getMyLocation();
		getBannmerApiPosition({position: 1}).then(res => {
			if(res.data && res.data.length) {
				this.bannerList = res.data;
			}
		})
		this.cityChangeLonLat = new QQMapWX({
			key: 'BKPBZ-VDILD-5C64V-PAZOL-25RX3-WWBNY'
		})
		if(options.scene) {
			uni.navigateTo({
				url: '/pages/personalCenter/login?type=1&scene=' + options.scene
			})
		}
	},
	onShow() {
		const openLocation = uni.getStorageSync('openLocation');
		uni.removeStorageSync('openLocation');
		if(openLocation) {
			this.getMyLocation();
		}else {
			if(!uni.getStorageSync('lngAndLat')) {
				this.getMyLocation();
			}
		}
		// #ifdef MP-WEIXIN
			const token = uni.getStorageSync('token');
		// #endif
		// #ifdef H5
			const token = '2eae0f660b498bdc724dee1efa63407e';
			uni.setStorage({
				key: 'token', data: token
			})
		// #endif
		if(token) {
			this.token = token;
		}else {
			this.token = '';
		}
		getOffMemberNotice().then(res => {
			if(res.data && res.data.text) {
				if(res.data.time != uni.getStorageSync('popupAnnouncementTime')) {
					uni.setStorageSync('popupAnnouncementTime', res.data.time);
					this.popupAnnouncementAry = res.data.text.split('|');
					this.popupAnnouncementFrame = true;
				}
			}
		})
	},
	onShareAppMessage(res) {//分享给好友
		let title = '山雀壹®共享茶室',
			imageUrl = '/static/images/logo.png',
			mpId = 'wxf8003ea15566ecd1';
	    if (res.from === 'button') {// 来自页面内分享按钮
	        console.log('button', res)
			return {
				title, imageUrl, mpId,
				path: '/pages/index/index?shareCode=' + this.shareCode
			}
	    }else {
			return {
			    title, imageUrl, mpId,
			    path: '/pages/index/index'
			}
		}
	},
	onShareTimeline(res) {//分享到朋友圈
	    return {
	        title: '山雀壹®共享茶室',
	        type: 0,
	        summary: "",
	    }
	},
	methods: {
		getMyLocation() {
			// #ifdef MP-WEIXIN
				uni.getLocation({//当前位置
					type: 'gcj02',
					success:res1 => {
						if(res1 && res1.latitude && res1.longitude) {
							this.cityChangeLonLat.reverseGeocoder({
								location: (res1.latitude + ',' + res1.longitude),
								success:res2 => {
									console.log('获取当前位置成功', res2)
									this.cityText = res2.result.address_component.city;
									this.searchText = res2.result.address;
								}
							})
							this.lngAndLat.latitude = res1.latitude;
							this.lngAndLat.longitude = res1.longitude;
							uni.setStorageSync('lngAndLat', this.lngAndLat);
							this.getDataList1(res1.longitude, res1.latitude);
						}
					}, fail:err => {
						if (err.errMsg == "getLocation:fail auth deny") {
							this.goFixedPosition();
						}
					}
				})
			// #endif
			// #ifdef H5
				this.lngAndLat.latitude = 24.9075;
				this.lngAndLat.longitude = 118.58687;
				uni.setStorageSync('lngAndLat', this.lngAndLat);
				this.getDataList1(118.58687, 24.9075);
			// #endif
		},
		getDataList1(lng, lat) {//lng经度 lat纬度
			isMemberGetTeaList({
				lng, lat,
				type: this.teaHourseId
			}).then(res2 => {
				if(res2.data && res2.data.length) {
					this.tesHourseList = res2.data;
					this.tesHourseList.forEach(item => {
						item.distance = Number(item.distance).toFixed(2);
						if(item.banner) {
							item.banZero = imgNetUrl + item.banner.split(',')[0];
						}else {
							item.banZero = '/static/images/logo.png';
						}
					})
					console.log()
				}else {
					this.tesHourseList = [];
				}
			})
		},
		goFixedPosition() {
			uni.showModal({
				title: '提示', confirmColor: '#99c043',
				content: '检测到您没打开获取信息功能权限，是否去设置打开？',
				success:res1 => {
					if (res1.confirm) {
						uni.setStorageSync('openLocation', true);
						uni.openSetting({
							success:res2 => { }
						})
					} else {
						this.cityIndex = 0;
						this.cityToLonLat(1);
					}
				}
			})
		},
		cityToLonLat(type) {
			this.cityChangeLonLat.geocoder({
				address: this.cityAry[this.cityIndex].city,
				success:res1 => {
					console.log('城市名转经纬度成功', res1)
					if(type == 1) this.cityText = res1.result.address_components.city;
					this.searchText = res1.result.address_components.province + res1.result.address_components.city + res1.result.address_components.district;
					this.lngAndLat.latitude = res1.result.location.lat;
					this.lngAndLat.longitude = res1.result.location.lng;
					uni.setStorageSync('lngAndLat', this.lngAndLat);
					this.getDataList1(res1.result.location.lng, res1.result.location.lat);
				}
			})
		},
		cliPopupAnnouncementClose() {
			let url = this.popupAnnouncementAry[this.popupAnnouncementAry.length - 1];
			if(url != '') {
				if(url == '/pages/index/index' || url == '/pages/order/index' || url == '/pages/activityHome/index' || url == '/pages/newsTab/index' || url == '/pages/personalCenter/index') {
					this.popupAnnouncementFrame = false;
					uni.switchTab({ url })
				}else {
					this.goUrl(url);
				}
			}else {
				this.popupAnnouncementFrame = false;
			}
		},
		goUrl(url) {
			if(this.token) {
				uni.navigateTo({ url })
			}else {
				uni.navigateTo({ url: '/pages/personalCenter/login?type=2' })
			}
		},
		topTotalHeight(height) {
			// #ifdef MP-WEIXIN
				this.calcNum = height;
			// #endif
			// // #ifdef H5
			// 	this.calcNum = 10;
			// // #endif
		},
		cliCityFun() {
			this.cityFrame = true;
		},
		cliCityAry(index) {
			this.cityIndex = index;
			this.cityText = this.cityAry[index].city;
			this.cityFrame = false;
			this.cityToLonLat(2);
		},
		cliSearchInp() {
			uni.chooseLocation({
				success: (res) => {
					console.log('打开地图选地址成功', res)
					this.cityText = '城市';
					this.searchText = res.address;
					this.lngAndLat.latitude = res.latitude;
					this.lngAndLat.longitude = res.longitude;
					uni.setStorageSync('lngAndLat', this.lngAndLat);
					this.getDataList1(res.longitude, res.latitude);
				}
			});
		},
		cliRenewalGreen() {
			this.departureType = 1;
			this.getIngOrder(1);
		},
		cliDoorGreen() {
			this.departureType = 2;
			this.getIngOrder(2);
		},
		getIngOrder(type) {
			if(this.token) {
				this.$refs['haveInHandList'].getDataList0();
				this.departureFrame = true;
			}else {
				uni.navigateTo({ url: '/pages/personalCenter/login?type=2' })
			}
		},
		cliClose() {
			this.departureFrame = false;
		},
		openShareFrame(id) {
			getSwitchCode({
				token: this.token, id
			}).then(res2 => {
				console.log('end_time', res2.data)
				this.shareCode = res2.data;
				this.shareType = 1;
				this.showShareFrame = true;
			})
		},
		cliCloseShare() {
			this.showShareFrame = false;
		},
		cliBannrImg(item) {
			if(item.url) {
				if(item.url == '/pages/index/index' || item.url == '/pages/order/index' || item.url == '/pages/activityHome/index' || item.url == '/pages/newsTab/index' || item.url == '/pages/personalCenter/index') {
					uni.switchTab({ url: item.url })
				}else {
					this.goUrl(item.url)
				}
			}else {
				let urls = [],
					current = 0;
				this.bannerList.forEach((res, index) => {
					urls.push(res.path);
					if(item.path == res.path) current = index;
				})
				uni.previewImage({ urls, current })
			}
		},
		cliTeaHouseBtn(type, id) {
			if(type == this.teaHouseIdx) return;
			this.teaHouseIdx = type;
			this.teaHourseId = id;
			if(this.lngAndLat.longitude && this.lngAndLat.latitude) {
				this.getDataList1(this.lngAndLat.longitude, this.lngAndLat.latitude);
			}else {
				this.goFixedPosition();
			}
		},
		cliPhoneBlack(item1Tel) {
			uni.makePhoneCall({
				phoneNumber: item1Tel,
				success:res => {
					if(res) console.log('打电话', res)
				}
			});
		},
		cliTeaList(item1) {
			let newObj = JSON.parse(JSON.stringify(item1));
			delete newObj.roomList;
			uni.navigateTo({
				url: '/pages/index/teahouseDetail?type=1&item1=' + JSON.stringify(newObj)
			})
		},
		cliAddress(item1Lat, item1Lon, name, address) {//跳转可导航的地图
			mapNavigation(Number(item1Lat), Number(item1Lon), name, address);
		},
		openRoomList(openVal, index1, tid) {
			if(openVal) {
				console.log('关闭')
				this.tesHourseList[index1].openVal = false;
				this.$forceUpdate();
			}else {
				isMemberGetTeaRoomList({tid, number: 100}).then(res => {
					if(res.data && res.data.data.length) {
						this.tesHourseList[index1].roomList = res.data.data;
						this.tesHourseList[index1].openVal = true;
						this.$forceUpdate();
					}else {
						uni.showToast({
							title: '该茶室暂无开放房间', icon: 'none', duration: 3000
						})
					}
				})
			}
		},
		cliUseNow(tid, rid, hour, cardDiscount, originalCost) {
			this.rightOffObj.tid = tid;
			this.rightOffObj.rid = rid;
			this.rightOffObj.hourMin = hour;
			this.rightOffObj.cardDiscount = cardDiscount;
			this.rightOffObj.originalCost = originalCost;
			this.rightOffFrame = true;
			this.$refs['rightOffPage'].renovateRight();
		},
		closeRightOff() {
			this.rightOffFrame = false;
		},
		cliAdvanceReservation(tid, rid, hour, cardDiscount, originalCost) {
			this.advanceBookingObj.tid = tid;
			this.advanceBookingObj.rid = rid;
			this.advanceBookingObj.hour = hour;
			this.advanceBookingObj.cardDiscount = cardDiscount;
			this.advanceBookingObj.originalCost = originalCost;
			this.advanceBookingFrame = true;
			this.$refs['advanceBookingPage'].renovateColor();
		},
		closeAdvanceBooking() {
			this.advanceBookingFrame = false;
		},
	}
}
</script>

<style>
.uni-noticebar/*插件的滚动条*/ {border-radius: 40rpx;}
</style>
